import LoginApi from '@/api/login'
import { TokenUtil } from "@lowcode/jpaas-common-lib"
import Cookies from 'js-cookie';
import {
  getState,
  client_id,
  getAuthorizeUri
} from "@public/public";
let vueappportal = process.env.VUE_APP_PORTAL;
const user = {
  namespaced: true,
  state: {
    userId: '',
    token: '',
    name: '',
    avatar: '',
    roles: [],
    buttons: [], // 按钮权限
    info: {},
    rootPath: '',
    loginType: '',
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, { name }) => {
      state.name = name

    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_BUTTONS: (state, buttons) => {
      state.buttons = buttons
    },
    SET_USERID: (state, userId) => {
      state.userId = userId
    },
    SET_ROOTPATH: (state, rootPath) => {
      state.rootPath = rootPath
    },
    SET_LOGIN_TYPE: (state, loginType) => {
      state.loginType = loginType
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        LoginApi.login(userInfo).then(res => {
          const result = res.data
          TokenUtil.setToken(result.accessToken.access_token);
          commit('SET_TOKEN', result.accessToken.access_token)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 登录(手机号)
    LoginByMobile({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        LoginApi.loginByMobile(userInfo).then(res => {
          const result = res.data;
          TokenUtil.setToken(result.accessToken.access_token);
          commit('SET_TOKEN', result.accessToken.access_token)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },
    //微信OpenId自动登录
    AutoLoginByWxId({ commit }, params) {
      return new Promise((resolve, reject) => {
        LoginApi.autoLoginByWxId(params).then(res => {
          TokenUtil.setToken(res.data);
          commit('SET_TOKEN', res.data)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },
    //钉钉用户Id自动登录
    AutoLoginByDdId({ commit }, params) {
      return new Promise((resolve, reject) => {
        LoginApi.autoLoginByDdId(params).then(res => {
          TokenUtil.setToken(res.data);
          commit('SET_TOKEN', res.data)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 免密登录
    AuthorizeLogin({ commit }, code) {
      return new Promise((resolve, reject) => {
        LoginApi.authorize(code).then(res => {
          const result = res.data;
          TokenUtil.setToken(res.data);
          commit('SET_TOKEN', result.accessToken.access_token)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 登出
    Logout({ commit, state }) {
      return new Promise((resolve) => {
        LoginApi.logout(state.token).then(() => {
          if (!vueappportal || vueappportal === 'false') {
            resolve()
          }
        }).catch(() => {
          resolve()
        }).finally(() => {
          commit('SET_TOKEN', '')
          Cookies.remove("IdToken")
          Cookies.remove("AccessToken")
          Cookies.remove("Authorization")
          Cookies.remove("XXL_JOB_LOGIN_IDENTITY")
          Cookies.remove("AUTHORIZATION_TOKEN");
          Cookies.remove("LOGIN_TYPE");
          TokenUtil.removeToken();

          if (vueappportal === 'true' || vueappportal == true) {
            sessionStorage.removeItem("state");
            sessionStorage.removeItem("visitUri");
            let state = getState();
            sessionStorage.setItem("state", state);
            //构建调整url
            getAuthorizeUri(state, client_id, function (authorizeUri, data) {
              sessionStorage.setItem("visitUri", data.redirect_uri);
              window.open(authorizeUri, '_self');
            });
          }
        })
      })
    },
    // cas验证ticket并免密登录
    AuthorizeTicketLogin({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        LoginApi.loginByTicket(userInfo).then(res => {
          const result = res.data;
          //请求返回体加密时：token = result.value
          let token = result.accessToken.access_token || result.value;
          TokenUtil.setToken(token);
          commit('SET_TOKEN', token);
          resolve(res)
        }).catch(error => {
          reject(error)
        });
      });
    },
    //根据第三方授权code自动登录
    AutoLoginByCode({ commit }, params) {
      return new Promise((resolve, reject) => {
        LoginApi.autoLoginByCode(params).then(res => {
          const result = res.data;
          //请求返回体加密时：token = result.value
          let token = result.access_token || result.value;
          TokenUtil.setToken(token);
          commit('SET_TOKEN', token)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },
  }
}

export default user
